home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 12322 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.7 KB  |  54 lines

  1. Path: news.ichange.com!newsmaster
  2. From: Jesse Liberty <jl@staff.ichange.com>
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Help! Newbie question ...
  5. Date: Tue, 19 Mar 1996 07:49:08 -0500
  6. Organization: AT&T
  7. Message-ID: <314EAD44.B20@staff.ichange.com>
  8. References: <4ilkfu$41q@Kaos.deepcove.com>
  9. NNTP-Posting-Host: 140.244.99.60
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 2.0 (Win95; I)
  14. CC: jl@staff.ichange.com
  15.  
  16. Sean Affleck wrote:
  17. > Is this legal ?
  18. > class A {...};
  19. > A f();
  20. > main() {
  21. >   A a = f();
  22. > }
  23. > A f()
  24. > {
  25. >    A fa;
  26. >    return fa;
  27. > }
  28.  
  29. You CAN do this but you almost certainly don't want to.  You are creating a local A object in your f() function and returning 
  30. it by value. That means a copy of the A object is being created on the stack which is very inefficient.  You'll almost 
  31. certainly want to return by reference, but then you have a far bigger problem. You certainly don't want to return a reference 
  32. to fa because it will go out of scope and be destroyed at the end of your function call.
  33.  
  34. The right answer, as you suspected is to change fa to be a pointer to A and to allocate space on the heap and return the 
  35. pointer. This gives you efficiency and safety but raises a design question: why is A allocating an objec to be used 
  36. elsewhere? It usually makes sense to allocate the object in whatever function is going to then own it.  There are exceptions, 
  37. but you'd have to ask yourself why you're doing it this way.
  38.  
  39. -j
  40.  
  41. ------
  42. Jesse Liberty [AT&T New Media Services]
  43. jl@staff.ichange.com    ZDNet: 72241,72
  44. Teach Yourself C++ In 21 Days. Sams 1994
  45. Teach Yourself MORE C++ In 21 Days. Sams 1996
  46. Teach Yourself ANSI C++ In 21 Days. Sams 1996
  47. C++: An Introduction To Programming. Que 1996
  48.